﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace Feng.DbHelper
{
    /// <summary>
    /// 数据库帮助类
    /// </summary>
    public class MssqlHelper
    {
        #region 字段属性
        /// <summary>
        /// 数据库连接字符串
        /// </summary>
        private static string conn = "Data Source=.;Initial Catalog=Cnblogs;User ID=sa;Password=123";
        #endregion

        #region DataTable写入数据
        public static void GetData(string title, string url, string author, string time, string motto, string depth, DataTable dt)
        {
            DataRow dr;

            dr = dt.NewRow();
            dr["BlogTitle"] = title;
            dr["BlogUrl"] = url;
            dr["BlogAuthor"] = author;
            dr["BlogTime"] = time;
            dr["BlogMotto"] = motto;
            dr["BlogDepth"] = depth;

            //2.0 将dr追加到dt中
            dt.Rows.Add(dr);
        }
        #endregion

        #region 插入数据到数据库
        /// <summary>
        /// 插入数据到数据库
        /// </summary>
        public static void InsertDb(DataTable dt)
        {
            try
            {
                using (System.Data.SqlClient.SqlBulkCopy copy = new System.Data.SqlClient.SqlBulkCopy(conn))
                {
                    //3.0.1 指定数据插入目标表名称
                    copy.DestinationTableName = "BlogArticle";

                    //3.0.2 告诉SqlBulkCopy对象 内存表中的 OrderNO1和Userid1插入到OrderInfos表中的哪些列中
                    copy.ColumnMappings.Add("BlogTitle", "BlogTitle");
                    copy.ColumnMappings.Add("BlogUrl", "BlogUrl");
                    copy.ColumnMappings.Add("BlogAuthor", "BlogAuthor");
                    copy.ColumnMappings.Add("BlogTime", "BlogTime");
                    copy.ColumnMappings.Add("BlogMotto", "BlogMotto");
                    copy.ColumnMappings.Add("BlogDepth", "BlogDepth");

                    //3.0.3 将内存表dt中的数据一次性批量插入到OrderInfos表中
                    copy.WriteToServer(dt);
                    dt.Rows.Clear();
                }
            }
            catch (Exception)
            {
                dt.Rows.Clear();

            }
        }
        #endregion

    }
}
